interface CacheItem {
  value: string
  expireTime: number
}

export class Cache {
  private cache: Map<string, CacheItem>

  constructor() {
    this.cache = new Map()
  }

  /**
   * 获取缓存
   * @param key 缓存键
   * @returns 缓存值,如果不存在或已过期返回null
   */
  async get(key: string): Promise<string | null> {
    const item = this.cache.get(key)
    if (!item) return null

    // 检查是否过期
    if (Date.now() > item.expireTime) {
      this.cache.delete(key)
      return null
    }

    return item.value
  }

  /**
   * 设置缓存
   * @param key 缓存键
   * @param value 缓存值
   * @param ttl 过期时间(毫秒)
   */
  async set(key: string, value: string, ttl: number): Promise<void> {
    this.cache.set(key, {
      value,
      expireTime: Date.now() + ttl
    })
  }

  /**
   * 删除缓存
   * @param key 缓存键
   */
  async delete(key: string): Promise<void> {
    this.cache.delete(key)
  }

  /**
   * 清空缓存
   */
  async clear(): Promise<void> {
    this.cache.clear()
  }

  /**
   * 清理过期缓存
   */
  async cleanup(): Promise<void> {
    const now = Date.now()
    for (const [key, item] of this.cache.entries()) {
      if (now > item.expireTime) {
        this.cache.delete(key)
      }
    }
  }
}
